package com.qf.shiro;

import com.qf.dao.PermissionDao;
import com.qf.dao.UserDao;
import com.qf.pojo.TbSysPermission;
import com.qf.pojo.TbSysUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

/**
 * @author H
 * @create 2020-10-14 23:54
 * @Description:
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserDao userDao;
    @Autowired
    PermissionDao permissionDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        List<TbSysPermission> permissionByLoginName = permissionDao.findPermissionByLoginName(primaryPrincipal);

        HashSet<String> objects = new HashSet<>();

        for (TbSysPermission per:permissionByLoginName
        ) {
            objects.add(per.getPerName());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(objects);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();

        TbSysUser passwordByLoginName = userDao.findPasswordByLoginName(username);

        return new SimpleAuthenticationInfo(username,passwordByLoginName.getPassword(),getName());
    }
}
